package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> localDateList = getDateList(begin, end);

        //select sum(amount) from order where status = 5 and delivery_time > begin and delivery_time < end
        List<Double> amountList = new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("beginTime", localDateTimeBegin);
            map.put("endTime", localDateTimeEnd);
            map.put("status", Orders.COMPLETED);
            Double amount = orderMapper.turnoverStatistics(map);
            if (amount == null)
                amount = 0.0;
            amountList.add(amount);
        }

        String dateListTotal = StringUtils.join(localDateList, ",");
        String amountListTotal = StringUtils.join(amountList, ",");
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(dateListTotal)
                .turnoverList(amountListTotal)
                .build();

        return turnoverReportVO;
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer TotalOrderCount = new Integer(0);
        Integer validOrderCount = new Integer(0);


        List<LocalDate> localDateList = getDateList(begin, end);

        for (LocalDate localDate : localDateList) {
            Integer number = 0;

            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);

            //订单总数量
            HashMap<Object, Object> map = new HashMap<>();

            //每日订单数量
            map.put("beginTime", localDateTimeBegin);
            map.put("endTime", localDateTimeEnd);
            number = orderMapper.getOrderCountList(map);
            orderCountList.add(number);
            TotalOrderCount += number;

            //每日有效订单数
            map.put("status", Orders.COMPLETED);
            number = orderMapper.getOrderCountList(map);
            validOrderCountList.add(number);
            validOrderCount += number;

        }


        OrderReportVO orderReportVO = new OrderReportVO();

        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        orderReportVO.setDateList(StringUtils.join(localDateList, ","));

        //每日订单数，以逗号分隔，例如：260,210,215
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList, ","));

        //每日有效订单数，以逗号分隔，例如：20,21,10
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList, ","));

        //订单总数
        orderReportVO.setTotalOrderCount(TotalOrderCount);

        //有效订单数
        orderReportVO.setValidOrderCount(validOrderCount);

        Double i = Double.valueOf(validOrderCount) / Double.valueOf(TotalOrderCount);
        //订单完成率
        orderReportVO.setOrderCompletionRate(i);


        return orderReportVO;
    }

    /**
     * 查询销量前10的商品
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime localDateTimeBegin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime localDateTimeEnd = LocalDateTime.of(end, LocalTime.MAX);

        HashMap<Object, Object> map = new HashMap<>();
        map.put("beginTime", localDateTimeBegin);
        map.put("endTime", localDateTimeEnd);
        map.put("status", Orders.COMPLETED);

        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.selectTop10(map);


        List<String> nameList = goodsSalesDTOList.stream().map(x -> {
                    String name = x.getName();
                    return name;
                }
        ).collect(Collectors.toList());

        List<Integer> numberList = goodsSalesDTOList.stream().map(x -> {
            Integer number = x.getNumber();
            return number;
        }).collect(Collectors.toList());

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();

        return salesTop10ReportVO;
    }


    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> localDateList = getDateList(begin, end);


        ArrayList<Object> arrayList = new ArrayList<>();

        ArrayList<Integer> totalUser = new ArrayList<>();
        ArrayList<Integer> createUser = new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            HashMap<Object, Object> map = new HashMap<>();
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);

            //用户总量
            //select count(id) from user where create_time < end
            map.put("endTime", localDateTimeEnd);
            Integer number = userMapper.userStatistics(map);
            totalUser.add(number);

            //新增用户
            //select count(id) from user where create_time < end and create_time > begin
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            map.put("beginTime", localDateTimeBegin);
            Integer number2 = userMapper.userStatistics(map);
            createUser.add(number2);
        }

        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(localDateList, ","));
        userReportVO.setTotalUserList(StringUtils.join(totalUser, ","));
        userReportVO.setNewUserList(StringUtils.join(createUser, ","));
        return userReportVO;
    }


    /**
     * 导出营业数据报表
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {

        //查询数据库，获取营业数据
        LocalDate now = LocalDate.now();
        LocalDateTime begin = LocalDateTime.of(now.minusDays(30), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(now.minusDays(1), LocalTime.MAX);

        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        //通过POI将数据写入Excel文件

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook workbook = new XSSFWorkbook(in);

            //填充数据 - 时间
            XSSFSheet sheet1 = workbook.getSheet("Sheet1");

            sheet1.getRow(1).getCell(1).setCellValue("时间:" + begin + "至" + end);

            XSSFRow row = sheet1.getRow(3);
            //填充数据 - 营业额
            row.getCell(2).setCellValue(businessData.getTurnover());
            //填充数据 - 完成率
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //填充数据 - 新增用户数
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());


            //填充明细数据
            for (int i = 0; i < 30; i++) {

                LocalDate now1 = LocalDate.now();
                LocalDate localDate= now1.plusDays(-30 + i);

                LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
                LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);

                BusinessDataVO businessData1 = workspaceService.getBusinessData(localDateTimeBegin,localDateTimeEnd);

                row = sheet1.getRow(7 + i);

                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());

            }

            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);


            outputStream.flush();
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }



    /**
     * 获取日期集合
     *
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {

        List<LocalDate> localDateList = new ArrayList<>();
        LocalDate beginTime = begin;
        localDateList.add(begin);
        while (!beginTime.equals(end)) {
            beginTime = beginTime.plusDays(1);
            localDateList.add(beginTime);
        }
        return localDateList;
    }
}
